package com.gpframework.module.controller.common;

import com.google.code.kaptcha.Producer;
import com.gpframework.common.config.GpframeworkConfig;
import com.gpframework.common.constant.Constants;
import com.gpframework.common.core.domain.AjaxResult;
import com.gpframework.common.core.redis.RedisCache;
import com.gpframework.common.utils.file.FileUploadUtils;
import com.gpframework.common.utils.uuid.IdUtils;
import com.gpframework.framework.config.ServerConfig;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 *
 * @Author gpframework
 */

/**
 * @Api(tags = "系统登录")
 */
@SuppressWarnings({"rawtypes"})
@RestController
public class CaptchaController {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    // 验证码类型

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    @ApiOperation("获取登录验证码")
    public Map getCode(HttpServletResponse response) throws IOException {
        // 保存验证码信息
        String uuid = IdUtils.simpleUuid();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;
        String randomCode = null;
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", "操作成功");
        // 生成验证码
        if ("math".equals(GpframeworkConfig.getCaptchaType())) {
//            String capText = captchaProducerMath.createText();
//            capStr = capText.substring(0, capText.lastIndexOf("@"));
//            code = capText.substring(capText.lastIndexOf("@") + 1);
            // 生成随机4位数字
            randomCode = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
            capStr = randomCode;
            code = randomCode;
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(GpframeworkConfig.getCaptchaType())) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }
        //("captcha code = " + capStr);

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            result.put("code", 500);
            result.put("msg", e.getMessage());
            return result;
        }

        result.put("uuid", uuid);
//        result.put("img", Base64.encode(os.toByteArray()));
        result.put("img", randomCode);
        return result;
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = GpframeworkConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = ServerConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            Map<String, Object> result = new HashMap<>();
            result.put("fileName", fileName);
            result.put("originalFilename", file.getOriginalFilename());
            result.put("fileType", file.getContentType());
            result.put("url", url);
            ajax.setData(result);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

}
